package ticker

import react.*
import react.dom.*
import kotlinx.browser.*
import kotlinx.dom.removeClass
import kotlinx.html.InputType
import kotlinx.html.button
//js事件库必须引入
import kotlinx.html.js.*
import kotlinx.html.onChange
import org.w3c.dom.HTMLButtonElement
import org.w3c.dom.HTMLInputElement
import org.w3c.dom.events.Event


interface TickerProps : RProps {
    var startFrom: Int
    var name: String
}

interface TickerState : RState {
    var secondsElapsed: Int
    var count:Int
    var h3Class:String
}

class Ticker(props: TickerProps) : RComponent<TickerProps, TickerState>(props) {
    override fun TickerState.init(props: TickerProps) {
        secondsElapsed = props.startFrom
        count=0
        h3Class="red-font"
    }

    var timerID: Int? = null

    override fun componentDidMount() {
        timerID = window.setInterval({
            // actually, the operation is performed on a state's copy, so it stays effectively immutable
            setState { secondsElapsed += 1 }
        }, 1000)
    }

    override fun componentWillUnmount() {
        window.clearInterval(timerID!!)
    }

    override fun RBuilder.render() {
            h2 {
                +"This app has been running for ${state.secondsElapsed} seconds."
            }
            input(type = InputType.text,name = "itemText"){
                key = "itemText"
                attrs {
                    onChangeFunction={
                        val target = it.target as HTMLInputElement
                        console.log(target.value)
                    }
                }
            }
            h3 (state.h3Class){  +"Hello,${props.name}"}
            for (index in 1..3){
                button{
                    +"add ${state.count} ${index}"
                    attrs {
                        var _self= this

                        onClickFunction={
                            val target = it.target as HTMLButtonElement

                            updataCount(it)
                            changeFontColor()
                            console.log(target)
                        }
                    }
                }
            }

    }

    private fun updataCount(it:Event) {
//        console.log(it)
        setState{
            count+=1
        }
    }
    private fun changeFontColor() {
//        console.log(it)
        if(state.h3Class.equals("")){
            setState{
                h3Class="red-font"
            }
        }else{
            setState{
                h3Class=""
            }
        }

    }
}

fun RBuilder.ticker(startFrom: Int = 0,name:String="TOM") = child(Ticker::class) {
    attrs.startFrom = startFrom
    attrs.name=name
}
